<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { showToast } from 'vant';
import { axiosrmedical } from '@/http/axiosRead';

interface Campus {
  id: number;
  campusName: string;
  campusAddr: string;
}

interface Department {
  id: number;
  departmentName: string;
  departmentDesc?: string;
  children?: Department[];
}

const router = useRouter();
const route = useRoute();
const patientId = ref(route.query.patientId as string);
const patientName = ref(route.query.patientName as string);

const campusList = ref<Campus[]>([]);
const departmentList = ref<Department[]>([]);
const loading = ref(false);
const activeCampus = ref(0);
const activeMainDept = ref<Department | null>(null);

// 获取院区列表
const fetchCampusList = async () => {
  loading.value = true;
  try {
    const res = await axiosrmedical.get('/Campus/GetCampus');
    if (res.data && res.data.code === 200) {
      campusList.value = res.data.data || [];
      if (campusList.value.length > 0) {
        activeCampus.value = campusList.value[0].id;
        fetchDepartmentsByCampus(activeCampus.value);
      }
    } else {
      showToast(res.data?.msg || '获取院区列表失败');
    }
  } catch (error) {
    console.error('获取院区列表出错:', error);
    showToast('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 根据院区ID获取科室列表
const fetchDepartmentsByCampus = async (campusId: number) => {
  loading.value = true;
  try {
    // 构建接口URL
    const url = `/Department/GetDepartmentCascadeByCampus`;
    console.log('请求科室列表接口:', url, '参数:', { campusId });
    
    const res = await axiosrmedical.get(url, {
      params: { campusId }
    });
    
    console.log('接口返回数据:', res.data);
    
    if (res.data && res.data.code === 200) {
      departmentList.value = res.data.data || [];
      if (departmentList.value.length > 0) {
        activeMainDept.value = departmentList.value[0];
      } else {
        activeMainDept.value = null;
      }
    } else {
      showToast(res.data?.msg || '获取科室列表失败');
    }
  } catch (error) {
    console.error('获取科室列表出错:', error);
    // 使用模拟数据以便测试界面展示
    showToast('使用模拟数据');
    console.log('使用模拟数据');
    
    // 模拟数据
    departmentList.value = [
      {
        id: 11,
        departmentName: "内科",
        children: [
          {
            id: 111,
            departmentName: "消化内科",
            departmentDesc: "呼吸内科"
          },
          {
            id: 112,
            departmentName: "血液内科",
            departmentDesc: "呼吸内科"
          }
        ]
      },
      {
        id: 12,
        departmentName: "外科",
        children: []
      },
      {
        id: 13,
        departmentName: "男科",
        children: [
          {
            id: 131,
            departmentName: "精神科",
            departmentDesc: "呼吸内科"
          }
        ]
      }
    ];
    
    if (departmentList.value.length > 0) {
      activeMainDept.value = departmentList.value[0];
    }
  } finally {
    loading.value = false;
  }
};

// 切换院区
const changeCampus = (campusId: number) => {
  activeCampus.value = campusId;
  fetchDepartmentsByCampus(campusId);
};

// 切换主科室
const changeMainDept = (dept: Department) => {
  activeMainDept.value = dept;
};

// 选择科室
const selectDepartment = (department: Department) => {
  router.push({
    path: '/doctor-schedule',
    query: { 
      patientId: patientId.value,
      patientName: patientName.value,
      campusId: activeCampus.value.toString(),
      departmentId: department.id.toString(),
      departmentName: department.departmentName
    }
  });
};

// 返回上一页
const onBack = () => {
  router.back();
};

onMounted(() => {
  fetchCampusList();
});
</script>

<template>
  <div class="department-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      title="选择科室" 
      left-arrow 
      @click-left="onBack">
      <template #right>
        <div class="nav-icons">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="circle-btn"></span>
        </div>
      </template>
    </van-nav-bar>

    <div class="scrollable-content">
      <!-- 院区选择 -->
      <div class="campus-tabs">
        <div 
          v-for="campus in campusList" 
          :key="campus.id"
          class="campus-tab"
          :class="{ active: activeCampus === campus.id }"
          @click="changeCampus(campus.id)"
        >
          {{ campus.campusName }}
        </div>
      </div>
      
      <van-loading v-if="loading" class="loading" size="24px" vertical>加载中...</van-loading>
      
      <template v-else>
        <div class="department-container">
          <!-- 主科室列表 -->
          <div class="main-department-list">
            <div 
              v-for="dept in departmentList" 
              :key="dept.id"
              class="main-department-item"
              :class="{ active: activeMainDept?.id === dept.id }"
              @click="changeMainDept(dept)"
            >
              {{ dept.departmentName }}
            </div>
          </div>
          
          <!-- 子科室列表 -->
          <div class="sub-department-list">
            <template v-if="activeMainDept?.children && activeMainDept.children.length > 0">
              <div 
                v-for="subDept in activeMainDept.children" 
                :key="subDept.id"
                class="sub-department-item"
                @click="selectDepartment(subDept)"
              >
                <div class="department-name">{{ subDept.departmentName }}</div>
                <div class="department-desc" v-if="subDept.departmentDesc">{{ subDept.departmentDesc }}</div>
              </div>
            </template>
            <div v-else-if="activeMainDept" class="sub-department-item" @click="selectDepartment(activeMainDept)">
              <div class="department-name">{{ activeMainDept.departmentName }}</div>
            </div>
            <div v-else class="empty-tip">
              该院区暂无科室
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<style scoped>
.department-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f8f9fa;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

.nav-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dot {
  width: 6px;
  height: 6px;
  background: #d8d8d8;
  border-radius: 50%;
  display: inline-block;
}

.circle-btn {
  width: 18px;
  height: 18px;
  border: 1.5px solid #d8d8d8;
  border-radius: 50%;
  display: inline-block;
  margin-left: 6px;
}

.campus-tabs {
  display: flex;
  background-color: #fff;
  overflow-x: auto;
  white-space: nowrap;
  -webkit-overflow-scrolling: touch;
  border-bottom: 1px solid #f0f0f0;
}

.campus-tab {
  padding: 12px 24px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  flex-shrink: 0;
  position: relative;
}

.campus-tab.active {
  color: #4080ff;
  font-weight: 500;
}

.campus-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 3px;
  background-color: #4080ff;
  border-radius: 3px;
}

.department-container {
  display: flex;
  height: calc(100vh - 130px);
}

.main-department-list {
  width: 30%;
  background-color: #f5f7fa;
  overflow-y: auto;
  border-right: 1px solid #eee;
}

.main-department-item {
  padding: 16px 12px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #eee;
}

.main-department-item.active {
  background-color: #fff;
  color: #4080ff;
  font-weight: 500;
  position: relative;
}

.main-department-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 16px;
  background-color: #4080ff;
  border-radius: 0 3px 3px 0;
}

.sub-department-list {
  width: 70%;
  overflow-y: auto;
  background-color: #fff;
}

.sub-department-item {
  display: flex;
  flex-direction: column;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.department-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.department-desc {
  font-size: 13px;
  color: #999;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 30px 0;
}

.empty-tip {
  padding: 30px 0;
  text-align: center;
  color: #999;
}
</style> 